// -----------------------------------------------------------
// Game Framework
// Copyright © 2024-2024 deadcycle. All rights reserved.
// Homepage: https://deadcycle.gitee.io
// Feedback: deadcycle@163.com
// -----------------------------------------------------------

using System.Collections.Generic;

using UnityEngine;

namespace ComponentAutoBind.Editor
{
    /// <summary>
    /// 自动绑定规则辅助器抽象类。
    /// </summary>
    public abstract class AutoBindRuleHelperBase : IAutoBindRuleHelper
    {
        /// <summary>
        /// 命名前缀与类型的映射。
        /// </summary>
        protected Dictionary<string, string> m_PrefixesDict = null;

        /// <summary>
        /// 反向查找映射。
        /// </summary>
        protected Dictionary<string, string> m_ReversePrefixesDict = null;

        /// <summary>
        /// 初始化自动绑定规则配置。
        /// </summary>
        public abstract void InitAutoBindRule();

        public bool TryParseBindComponent(Transform target, List<string> fieldNames, List<string> componentTypeNames)
        {
            string[] strArray = target.name.Split('_');

            if (strArray.Length == 1)
            {
                return false;
            }

            // ReSharper disable once UseIndexFromEndExpression
            string fieldName = strArray[strArray.Length - 1];

            for (int i = 0; i < strArray.Length - 1; i++)
            {
                string str = strArray[i];
                string componentName;

                if (m_PrefixesDict.TryGetValue(str, out componentName))
                {
                    fieldNames.Add($"{str}{fieldName}");
                    componentTypeNames.Add(componentName);
                }
                else
                {
                    Debug.LogError($"[{target.name}]自动绑定失败， 命名中[{str}]不存在对应的组件类型，检查命名。");

                    return false;
                }
            }

            return true;
        }

        public string ParseFieldName(Component target)
        {
            string[] strArray = target.gameObject.name.Split('_');

            if (strArray.Length == 1)
            {
                return null;
            }

            // ReSharper disable once UseIndexFromEndExpression
            string fieldName = strArray[strArray.Length - 1];
            string str;

            return m_ReversePrefixesDict.TryGetValue(target.GetType().Name, out str) ? $"{str}{fieldName}" : null;
        }
    }
}